/**
 * Created by Administrator on 16-10-25.
 */
if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
WEB_SOCKET_DEBUG = true;
var  name, client_list={};
var private_user_list;

/**
 * @author mmy
 * 相关类的说明
 * ws  webSocket操作类
 * Chat  聊天类，主要处理到服务器的数据
 * Msg  消息类 主要处理客户端信息处理显示
 * Help 辅助类 例如刷新用户列表等等
 */


/**
 * 定义一个ws类
 * @type {{}}
 */
var ws = {
    socket:null,
    //链接socket
    connect:function(){
        this.socket = new WebSocket("ws://172.20.17.110:7272");
        this.socket.onopen = this.open;
        this.socket.onmessage = this.message;
        this.socket.onclose = this.close;
        this.socket.onerror = this.error;
    },
    //发送登录握手信息
    open:function(){
        var HomeUser = $("#HomeUserInfo").val();
        var HomeUserInfo = JSON.parse(HomeUser);
        console.log(HomeUserInfo);
        // 登录
        Chat.sendSocket({
            type:"login",
            room_id:HomeUserInfo['room_id'],
            userKey:HomeUserInfo['userKey']
        });
    },

    //有消息时，处理消息
    message:function(e){
        //var data = eval("("+ e.data+")");
        var data = JSON.parse(e.data);
        console.log(data);
        switch(data['type']){
            // 服务端ping客户端
            case 'ping':
                Chat.sendSocket({type:"pong"});
                break;
            // 登录 更新用户列表
            case 'login':
                //显示消息
                Chat.login(data);
                break;
            // 发言
            case 'say':
                if(data['to_client_id']!='all')
                {
                    //私聊
                    Msg.createHtml2(data);
                    break;
                }
                else
                {
                    //群聊
                    Msg.createHtml(data);
                    Help.rightButtonEvent();
                    break;
                }
            case 'status':
                Msg.statusMessage(data);
                break;
            // 用户退出 更新用户列表
            case 'logout':
                delete client_list[data['from_client_id']];
                Help.flushClientList();
        }
    },

    //socket关闭处理
    close:function(){
        console.log("连接关闭，定时重连");
        this.socket.connect();
    },
    //socket错误处理
    error:function(){
        console.log("出现错误！");
    }
};
ws.connect();
/**
 * @author mmy
 * 聊天处理类
 * @type {{}}
 */
var Chat = {

    // 登录聊天室
    login: function (data) {
        // 创建在线用户列表
        Help.createUserList(data);

        // 显示历史消息
        Msg.showHistoryList(data);

        //显示聊天消息
        // Msg.createHtml(data);
        //Help.makeUserList(data);
        // 刷新用户列表
        Help.flushClientList();

    },
    sendMessage:function(obj){
        if(typeof obj=='object')
        {
            obj.type = 'say';
        }
        return this.sendSocket(obj);
    },

    // 发送到socket
    sendSocket: function (obj) {
        ws.socket.send(JSON.stringify(obj));
        return false;
    },
    forbidUserTalk:function(){
        var userInfo = Help.userInfo();
        var forbid_data = {type:"status",status:"forbid_talk",room_id:"1",forbid_client_id:Help.user_id,forbid_client_name:Help.user_name,forbid_client_ip:Help.user_ip};
        this.sendSocket(forbid_data);
    },
    forbidUserIp:function(uid,username,ip){
        var userInfo = Help.userInfo();
        var forbid_data = {type:"status",status:"forbid_ip",room_id:"1",forbid_client_id:Help.user_id,forbid_client_name:Help.user_name,forbid_client_ip:Help.user_ip};
        this.sendSocket(forbid_data);
    }



};

/**
 * 消息处理类
 * @type {{}}
 */
var Msg = {

    //将消息推送到聊天框
    createHtml:function(data){
        // 发言
        console.log('群聊：data：');
        console.log(data);
        data['content'] = Help.translate(data['content']);//转换字符串中的标签，让图片可以显示
        var _html = ' <div class="talkRight_head "></div>'
            +'<div class="talkRight_content">'
            +'<div class="talkRight_img">'
            + "<img src="+data['image']+" width=\"30px\" height=\"30px\"/>"
            +  '<span class="padding username">'+data['from_client_name']+'</span>'
            + '<span class="padding">'+data['time']+'</span>'
            + '</div>'
            + '<div style="float: left">'
            +'<span class="talk_span">'+data['content']+'</span>'
            + '</div>'
            +'</div>';
        $("#userTalkContent").append(_html);
        var div = document.getElementById('userTalkContent');
        div.scrollTop = div.scrollHeight;

    },
    onsubmit:function(){
        var input = $("#chatText").html();
        if(input.length==0)
        {
            alert('请输入内容');
            return false;
        }
        Chat.sendMessage({
            to_client_id:'all',
            to_client_name:'所有人',
            content:input

        });

        $("#chatText").html('');
        return false;
    },
    showHistoryList:function(data){
        //没有对象元素 返回false
        if(!(data.hasOwnProperty('history_list'))){
            return false;
        }
        //有对象元素放回对象元素列表
        for(var i=(data['history_list']).length-1 ;i>=0;i--)
        {
            var res = JSON.parse(data['history_list'][i]);
            console.log(res);
            Msg.createHtml(res);
        }
    },
    createHtml2:function(data){
        var HomeUser = $("#HomeUserInfo").val();
        var HomeUserInfo = JSON.parse(HomeUser);
console.log('用户信息');
console.log(HomeUserInfo);
        console.log('私聊：data：');
        console.log(data);
        data['content'] = Help.translate(data['content']);
        if(HomeUserInfo['nickname']==data['from_client_name'])
        {
            var from_username = data['from_client_name'];
            //自己发的数据
            var  __html = "<div class='self_people_head'><img class='self_img' src='"+data['image']+"' /><span>"+data['from_client_name']+"</span><span>"+data['time']+"</span><div style='width: 200px;float: right'></div><p>"+data['content']+"</p></div></div>";
            console.log("自己发的数据");
            console.log(data);

            var uid = data['to_client_id'];
            console.log(uid);
            console.log(from_username);
            var clid = 'uid'+uid;
            $(".private_area_right_connect ."+clid+"").append(__html);
            $(".private_area_right_connect ."+clid+"").scrollTop =  $(".private_area_right_connect "+clid+"").scrollHeight;
        }
        else
        {
            console.log("收到数据");
            console.log(data);
            var  __html = "<div class='other_people_head'><img class='self_img' src='"+data['image']+"' /><span>"+data['from_client_name']+"</span><span>"+data['time']+"</span><div style='width: 200px;float: right'></div><p>"+data['content']+"</p></div></div>";

            //收到数据方处理
            var from_user_id = data['from_client_id'];
            var uid = 'uid'+from_user_id;
            var from_username = data['from_client_name'];
            var child = "<li class='active "+uid+"'>"+from_username+"<img id='private_close' class='private_close' dataid="+from_user_id+" username='"+from_username+"' src='/Public/home/images/icon/chat-close2.png' /></li>";
            var chatContentKuang = "<div class='private_area_right_class "+uid+"' uid="+from_user_id+" username="+from_username+"></div>";
            var chatContent ="<div class='other_people_head'><img class='other_img' src='"+data['image']+"'/><span>"+from_username+"</span><span>"+data['time']+"</span><div style='width: 200px;float: left'></div><p>"+data['content']+"</p></div>";
            //判断私聊列表里有无该用户 有显示，没有 推上去并显示
            if($(".private_area_user_li ."+uid+"").length)
            {
                console.log('有列表');
                $(".private_area_user_li li").removeClass('active');
                $(".private_area_user_li ."+uid+"").addClass('active');
            }
            else
            {
                console.log('无列表');
                $(".private_area_user_li li").removeClass('active');
                $(".private_area_user_li").append(child);
            }
            //聊天内容模块 有则推到相应的区域，没有则添加区域并显示内容
            if($(".private_area_right_connect ."+uid+"").length)
            {
                console.log('有聊天内容');
                $(".private_area_right_connect .private_area_right_class").css({display:"none"});
                $(".private_area_right_connect ."+uid+"").append(chatContent);
                $(".private_area_right_connect ."+uid+"").css({display:"block"});
            }
            else
            {
                console.log('无聊天内容');
                $(".private_area_right_connect .private_area_right_class").css({display:"none"});
                $(".private_area_right_connect").append(chatContentKuang);
                $(".private_area_right_connect ."+uid+"").append(chatContent);
                $(".private_area_right_connect ."+uid+"").css({display:"block"});
            }
            $("#user_title").html(from_username);
            $(".private_area_right_connect ."+uid+"").scrollTop =  $(".private_area_right_connect "+uid+"").scrollHeight;
        }
        $("#private_area").show();
    },
    statusMessage:function(data){
        switch(data['status']){
            case 'forbid_talk':
                alert(data['msg']);
                break;
            case 'forbid_ip':
                alert(data['msg']);
                break;
            case '':
                break;
            case '':
                break;
            case '':
                break;
            default :
                break;
        }
    }




};

/**
 * @author mmy
 * 辅助聊天类
 * @type {{}}
 */
var Help = {
    user_id:null,
    user_name:null,
    user_ip:null,

    makeUserList:function(data){
        if(data['client_list']){
            client_list = data['client_list']
        }
        else
        {
            client_list[data['userid']] = {
                'userid': data['userid'],
                'nickname': data['nickname'],
                'ip': data['ip'],
                'level': data['level'],
                'time': data['time']
            }
        }
    },
    //刷新在线用户列表
    flushClientList:function(){
        var userlist_window = $("#userList");
        userlist_window.empty();
        userlist_window.append('<div class="talkRight_list_head bottom_line"> 用户列表</div>');
        for(var p in client_list){
            userlist_window.append('<div class="talkRight_list_head bottom_line user_hover" uid="'+p+'" username="'+client_list[p]['nickname']+'" ip="'+client_list[p]['ip']+'" > '+client_list[p]['nickname']+'</div>');
        }

        this.rightButtonEvent();
    },

    //创建在线用户列表
    createUserList:function(data){
        if(data['client_list'])
        {
            client_list = data['client_list'];
        }
        else{
            client_list[data['userid']] = {
                'userid': data['userid'],
                'nickname': data['nickname'],
                'ip': data['ip'],
                'level': data['level'],
                'time': data['logintime']
            };
        }
    },

    translate:function(string){
        string = string.replace(/&lt;/g ,'<');//将&lt;转成<
        string = string.replace(/&quot;/g,'"');//将&quot;转成"
        string = string.replace(/&gt;/g,'>');//将&gt;转成>
        return string;
    },

    rightButtonEvent:function(){
        //右键出现禁言框
        var list = $('#userList .user_hover');
        for (var i = 0; i < list.length; i++) {
            list[i].oncontextmenu = function(e){
                var Ovent = e|| event;
                var uid= $(this).attr('uid');
                var username = $(this).attr('username');
                var user_ip = $(this).attr('ip');
                Help.user_id = uid;
                Help.user_name = username;
                Help.user_ip = user_ip;
                $(".privateButton").attr('uid',uid);
                $(".privateButton").attr('username',username);
                //获取当前用户信息，判断权限
                var HomeUser = $("#HomeUserInfo").val();
                var HomeUserInfo = JSON.parse(HomeUser);
                //判断用户权限，看用户是否有禁言，封ip权限
                if(HomeUserInfo['levelid']>0)
                {
                    $(".privateButton p").css({
                        display:'block'
                    });

                    $(".privateButton").css({
                        display:'block',
                        left:Ovent.clientX+'px',
                        top: Ovent.clientY + 'px'
                    });
                    return false;
                }
                else
                {
                    //游客 只能私聊
                    $(".privateButton p").eq(0).css({
                        display:'block'
                    });

                    $(".privateButton").css({
                        display:'block',
                        left:Ovent.clientX+'px',
                        top: Ovent.clientY + 'px'
                    });
                    return false;
                }
            };
        }
    },
    setPrivateUserData:function(){
        //获取到私聊框的用户 id  用户名
        var uid = $(".privateButton").attr('uid');
        var username = $(".privateButton").attr('username');
        $("#private_area").attr('uid',uid);
        $("#private_area").attr('username',username);
        var clid = 'uid'+uid;
        //自己不能和自己聊天
        var HomeUser = $("#HomeUserInfo").val();
        var HomeUserInfo = JSON.parse(HomeUser);
        if(uid == HomeUserInfo['userid'])
        {
            alert('不能和自己聊天');
            return false;
        }

        //判断用户是否已经存在私聊列表，存在则显示出来
        var len = $(".private_area_user_li ."+clid+"");
        if(len.length)
        {
            $("#user_title").html(username);
            $(".private_area_user_li li").removeClass('active');
            $(".private_area_user_li ."+clid+"").addClass('active');
            $(".private_area_right_class").css({display:'none'});
            $(".private_area_right_connect ."+clid+"").css({display:'block'});
            $("#private_area").show();
            return false;
        }
        //将用户名推到私聊列表 和顶部
        var child = "<li class='active uid"+uid+"'>"+username+"<img id='private_close' class='private_close' dataid="+uid+" username='"+username+"' src='/Public/home/images/icon/chat-close2.png' /></li>";
        var chatContent = "<div class='private_area_right_class uid"+uid+"' uid="+uid+" username="+username+">";
        //推送列表
        $(".private_area_user_li li").removeClass('active');
        $(".private_area_user_li").append(child);

        //推送聊天内容 有聊天内容，隐藏之前的
        var len = $(".private_area_right_class").length;
        if(len)
        {
            $(".private_area_right_class").css({display:'none'});
        }
        $(".private_area_right_connect").append(chatContent);
        $("#user_title").html(username);
        //给私聊人员列表关闭添加点击事件
        this.setPrivateListClick();
        //给私聊人员列表添加点击事件
        this.setPrivateListLiClick();
        //显示私聊区域
        $("#private_area").show();
    },
    //给私聊人员列表添加点击事件
    setPrivateListClick:function(){
        var privateList = $(".private_area_user_li #private_close");
        private_user_list = privateList.length;
        for(var i=0;i<privateList.length;i++)
        {
            privateList[i].onclick = function(ev){
                var events=ev||event;
                //移除当前用户的信息
                var uid = $(this).attr('dataid');
                var username =  $(this).attr('username');
                $(this).parent().remove();
                var cls = 'uid'+uid;
                $(".private_area_right_connect ."+cls+"").remove();
                //显示第一个用户信息
                private_user_list = private_user_list -1;
                //全局变量更新私聊列表个数
                if(private_user_list=='0')
                {
                    $(".private_area").css({display:'none'});
                }
                var tt = $(".private_area_user_li img").eq(0);
                $(".private_area_user_li li").removeClass('active');
                $(".private_area_user_li li").eq(0).addClass('active');
                var newUid = tt.attr('dataid');
                var newUsername = tt.attr('username');
                $("#user_title").html(newUsername);
                var clasid = 'uid'+newUid;
                $(".private_area_right_connect ."+clasid+"").css({display:'block'});
                //阻止冒泡事件
                Help.stopPropagation(events);
            }
        }

    },
    setPrivateListLiClick:function(event){
        var privateList = $(".private_area_user_li li");
        for(var i=0;i<privateList.length;i++)
        {
            privateList[i].onclick = function(){
                var uid = $(this).find('img').attr('dataid');
                var username =  $(this).find('img').attr('username');
                console.log(uid);
                console.log(username);
                $("#user_title").html(username);
                privateList.removeClass('active');
                $(this).addClass('active');
                var clasd = 'uid'+uid;
                $(" .private_area_right_connect .private_area_right_class").css({display:'none'});
                $(".private_area_right_connect ."+clasd+"").css({display:'block'});
            }
        }

    },
    stopPropagation:function(e){
        e = e || window.event;
        if(e.stopPropagation) { //W3C阻止冒泡方法
            e.stopPropagation();
        } else {
            e.cancelBubble = true; //IE阻止冒泡方法
        }
    },
    userInfo:function(){
        var HomeUser = $("#HomeUserInfo").val();
        var HomeUserInfo = JSON.parse(HomeUser);
        return HomeUserInfo;
    }



};

$(function(){
    //私聊点击
    $(".privateButton p").eq(0).on('click','',function(){
        //获取到私聊框的用户 id  用户名 并将值赋值到私聊框
        Help.setPrivateUserData();
    });
    //禁言
    $(".privateButton p").eq(1).on('click','',function(){
        //用户禁言方法
        var uid = $(".talkRight_list_head .user_hover").attr('uid');
        var username = $(".talkRight_list_head .user_hover").attr('username');
        var ip = $(".talkRight_list_head .user_hover").attr('ip');
        Chat.forbidUserTalk();
    });
    //封ip
    $(".privateButton p").eq(2).on('click','',function(){
        //获取到私聊框的用户 id  用户名 并将值赋值到私聊框
        var uid = $(".talkRight_list_head .user_hover").attr('uid');
        var username = $(".talkRight_list_head .user_hover").attr('username');
        var ip = $(".talkRight_list_head .user_hover").attr('ip');
        Chat.forbidUserIp();
    });
    //关闭私聊人员，清除窗口内容
    $("#private_submit").on('click',function(){
        var input = $("#chatText2").html();
        if(input.length==0)
        {
            alert('请输入内容');
            return false;
        }
        if(input.length>300)
        {
            alert('输入内容不能超过300字');
            return false;
        }
        var uid = $(".private_area_user_li .active img").attr('dataid');
        var username = $(".private_area_user_li .active img").attr('username');
        Chat.sendMessage({
            to_client_id:uid,
            to_client_name:username,
            content:input

        });

        $("#chatText2").html('');
        return false;

    });



/**------------------------------------------------------------------------------**/
    // 聊天框拖拽
    var disX=0;
    var disY=0;
    $('.private_area').on('mousedown',function(event) {
        disX=event.clientX-$('.private_area')[0].offsetLeft;
        disY=event.clientY-$('.private_area')[0].offsetTop;

        $(document).mousemove(function(event) {
            var l=event.clientX-disX;
            var t=event.clientY-disY;
            if(l<0)
            {
                l=0;
            }
            else if(l>document.documentElement.clientWidth-$('.private_area')[0].offsetWidth)
            {
                l=document.documentElement.clientWidth-$('.private_area')[0].offsetWidth;
            }
            if(t<0)
            {
                t=0;
            }
            else if(t>document.documentElement.clientHeight-$('.private_area')[0].offsetHeight)
            {
                t=document.documentElement.clientHeight-$('.private_area')[0].offsetHeight;
            }
            $('.private_area').css({
                left: l,
                top: t,
                marginTop:0,
                marginLeft:0
            });
        });
        $(document).mouseup(function(event) {
            $(document).off('mousemove');
            $(document).off('mouseup');
        });
        event.stopPropagation();
    });
});

